<script>
import {ref, computed} from 'vue';
import CustomButton from "@/components/button/index.vue";
import CustomTitle from "@/components/title/index.vue";
import SearchBox from "@/components/searchBox/index.vue";
import {deleteNote, generateSummary, getAllNotes, saveNote} from "@/api/api.js";
import {ElMessage} from "element-plus";
import {TokenService} from "@/stores/userStore.js";

export default {
  name: 'NoteManagement',
  components: {
    CustomButton,
    CustomTitle,
    SearchBox
  },
  setup() {

    const searchQuery = ref('');
    const summary = ref('');
    const noteList = ref([
      {
        id: 1,
        title: "Vue3 学习笔记",
        content: "Vue3 学习笔记...",
        date: "2022-01-01",
        isSelected: false
      },
      {
        id: 2,
        title: "Django 学习笔记",
        content: "Django 学习笔记...",
        date: "2022-01-01",
        isSelected: false
      },
      // Add more notes as needed
    ]);
    const currentNote = ref("")
    const currnetNoteId = ref(0)
    const input = ref("")
    const selectItem = (item) => {
      noteList.value.forEach(item => {
        item.isSelected = false
      })
      item.isSelected = true;
      currentNote.value = item.content;
      currnetNoteId.value = item.id;
      input.value = item.title;
    };

    const  transformNoteData=(noteData) =>{
      return {
        id: noteData.id,
        title: noteData.title,
        content: noteData.content,
        date: new Date(noteData.created_at).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }),
        isSelected: false
      };
    }
    // Computed property to filter notes based on search query
    const filteredNotes = computed(() => {
      if (!searchQuery.value) {
        return noteList.value;
      }
      return noteList.value.filter(note =>
        note.title.toLowerCase().includes(searchQuery.value.toLowerCase())
      );
    });
    selectItem(noteList.value[0])
    const addNote = () => {
      const newNote = {
        id: noteList.value.length + 1,
        title: "新笔记",
        date: "2025-02-15 12:30",
        content: "5555",
        isSelected: true,
      };
      noteList.value.push(newNote);
      selectItem(newNote);
    }
    // Function to handle note selection
    const doDeleteNote = () => {
      deleteNote(currnetNoteId.value).then(res => {
        if (!res.success) {
          console.log(res.message)
        } else {
          console.log(res.message)
          noteList.value = noteList.value.filter(note => note.id !== currnetNoteId.value)
          selectItem(noteList.value[0])
        }
      }).catch(err => {
        console.log(err.message)
      })
      noteList.value = noteList.value.filter(note => note.id !== currnetNoteId.value)
      selectItem(noteList.value[0])
    }
    const doGenerateSummary = () => {
      generateSummary(currentNote.value).then(res => {
        if (!res.success) {
          console.log(res.message)
        } else {
          console.log(res.message)
          summary.value = res.summary
        }
      }).catch(err => {
        console.log(err)
      })
    }
    const getAllNote = () => {
      const user_id =TokenService.getCurrentUserId()
      getAllNotes(user_id).then(res => {
        if (!res.success) {
          console.log(res.message)
        } else {
          console.log(res.message)
          let notes = res.notes.map(note => transformNoteData(note))
          noteList.value = notes
          selectItem(noteList.value[0])
        }
      }).catch(err => {
        console.log(err.message)
      })
    }
    getAllNote()
    const doSaveNote = () => {
      const user_id =TokenService.getCurrentUserId()
      saveNote(user_id, currnetNoteId.value, input.value, currentNote.value, summary.value).then(res => {
        if (!res.success) {
          console.log(res.message)
        } else {
          console.log(res.message)
        }
      }).catch(err => {
        console.log(err.message)
      })
    }
    return {
      noteList,
      searchQuery,
      filteredNotes,
      selectItem,
      summary,
      input,
      addNote,
      doDeleteNote,
      currentNote,
      doGenerateSummary,
      doSaveNote
    };
  }
};
</script>

<template>
  <div class="note-management">
    <div class="header">
      <CustomTitle :title="$t('note-summary.header.title')" icon="Notebook"></CustomTitle>
    </div>
    <div class="content">
      <div class="left" style="max-width: 400px;">
        <div class="search-box">
          <el-input v-model="searchQuery" :placeholder="$t('note-summary.left.searchNotes')"></el-input>
          <CustomButton :label="$t('note-summary.left.search')" @click="filteredNotes"></CustomButton>
        </div>
        <ul>
          <li v-for="item in filteredNotes"
              :key="item.id"
              class="note"
              :class="{ 'selected': item.isSelected }"
              @click="selectItem(item)">
            <div class="together">
              <div class="title">{{ item.title }}</div>
              <div class="date">{{ item.date }}</div>
            </div>
            <div class="body">{{ item.content }}</div>
          </li>
        </ul>
      </div>

      <div class="right">
        <div class="functionButtons">
          <CustomButton :label="$t('note-summary.header.newNote')" style="width: 110px;"
                        @click="addNote"></CustomButton>
          <CustomButton :label="$t('note-summary.right.generateSummary')" style="width: 110px;"
                        @click="doGenerateSummary"></CustomButton>
          <CustomButton :label="$t('note-summary.right.saveNote')" style="width: 110px;"
                        @click="doSaveNote"></CustomButton>
          <CustomButton :label="$t('note-summary.right.deleteNote')" style="width: 110px;"
                        @click="doDeleteNote"></CustomButton>
        </div>
        <div class="title">
          <el-input v-model="input" :placeholder="$t('note-summary.right.noteTitle')"></el-input>
        </div>
        <div style="display: flex;flex-direction: row;">
          <el-input
            v-model="currentNote"
            type="textarea"
            :rows="15"
            :placeholder="$t('note-summary.right.startWriting')"
            class="note-input"
          />
          <el-input
            v-model="summary"
            type="textarea"
            :rows="15"
            :placeholder="$t('note-summary.right.summary')"
            class="note-input"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

@import "/src/css/base.css";
@import "/src/css/note-management/index.css";

textarea.el-textarea__inner {
  height: 500px !important;
}

.note.selected {
  background-color: #f0f0f0;
}

.search-box {
  width: 100px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-input__inner {
  height: 100%;
  width: 70%;
}

.el-button {
  width: 20%;
  height: 70%;
  margin-left: 10%;
}

</style>
